import java.awt.BorderLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

import ros.*;
import ros.communication.*;

import ros.pkg.word_draw_processing.msg.*;

public class DrawFrameNode extends JFrame{

    private static DrawPApplet _drawpapplet;
    public DrawFrameNode(){
        super();

        addWindowListener(new WindowAdapter(){
		public void windowClosing(WindowEvent e) {
		    System.exit(0);
		}
	    });

        addComponentListener(new ComponentAdapter(){
		public void componentShown(ComponentEvent e) {
		    if(_drawpapplet !=null)
			_drawpapplet.redraw();
		}
		public void componentResized(ComponentEvent e) {
		    if(_drawpapplet !=null)
			_drawpapplet.redraw();
		}
	    });

        doMyLayout();
    }

    private void doMyLayout(){
        _drawpapplet =new DrawPApplet();
        _drawpapplet.init();

        setLayout(new BorderLayout());
        add(_drawpapplet,BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        try{
            JFrame f=new DrawFrameNode();
            f.pack();
            f.setLocation(100,100);
            f.setVisible(true);

	    final Ros ros = Ros.getInstance();
	    ros.init("DrawFrameNode");

	    //	    ros.pkg.std_msgs.msg.MultiArrayLayout mal = new ros.pkg.std_msgs.msg.MultiArrayLayout();
	    //	    WordDrawLayout wdl = new WordDrawLayout();

	    NodeHandle n = ros.createNodeHandle();

	    //	    Subscriber.Callback<ros.pkg.std_msgs.msg.MultiArrayLayout> callback =
	    //		new Subscriber.Callback<ros.pkg.std_msgs.msg.MultiArrayLayout>() {
	    //		public void call(ros.pkg.std_msgs.msg.MultiArrayLayout mal) {
	    //		    if(_drawpapplet !=null){
	    //			_drawpapplet.inputData(mal);
	    //			_drawpapplet.redraw();
	    //		    }
	    //		}
	    //	    };
	    Subscriber.Callback<WordDrawLayout> callback =
		new Subscriber.Callback<WordDrawLayout>() {
		public void call(WordDrawLayout wdl) {
		    if(_drawpapplet !=null){
			_drawpapplet.inputData(wdl);
			_drawpapplet.redraw();
		    }
		}
	    };

	    Subscriber<WordDrawLayout> sub;
	    sub = n.subscribe("chatter",
			      new WordDrawLayout(),
			      callback,
			      100);

	    n.spin();
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
